<?php
/*
 * @Author: your name
 * @Date: 2021-09-21 16:46:35
 * @LastEditTime: 2022-02-28 13:22:47
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /nlog/app/Http/Controllers/AdminController/Login.php
 */

namespace App\Http\Controllers\crm;

use Illuminate\Support\Facades\Request;
use App\Models\admin_model\Admins;                        // admins表
use App\Http\Controllers\redis\RedisController as Redis;

class Login extends BaseController
{

    public      $redisKey    =  CRM_LOGIN_REDIS_KEY;
    public      $headerKey    =  CRM_LOGIN_HEADER_KEY;


 


    /**
     * @description: 登录接口
     */
    public function index()
    {
        if (Request::has('userName') && Request::has('passWord')) {
            $userName = Request::input('userName');
            $md5_passWord = md5(Request::input('passWord'));
            return $this->login($userName, $md5_passWord);
        }
    }




    public function loginOut($die = true)
    {

        $token = $_SERVER[$this->headerKey];
        $key = $this->redisKey . $token;
        if ($token && Redis::existSKey($key, ['RedisDB' => 11])) {
            Redis::del($key, ['RedisDB' => 11]);
        }
        if($die){
            return $this->create(200, '退出成功');
        }
    }


    /**
     * @description: 登录方法
     * @param   userName
     * @param   passWord
     * @return  
     */
    protected function login($userName, $passWord, $die = true)
    {
        $res =   Admins::login($userName, $passWord);
        if ($res) {
            if ($res['status'] == 0  ) {
                return    $this->create(100, '该账号已经禁用');
            }else if(!$res['division_id']){
                return    $this->create(100, '该账号没有选择所属部门');
            } else {
                $redisKey   =  $this->redisKey;
                $token = md5(create_uuid($redisKey));
                $key =  $redisKey . $token;
                Redis::redisSet($key, $res['id'], 7 * 24 * 3600, ['RedisDB' => 11]);            //一个星期过期
                return $die ? $this->create(200, '登录成功', ['token' =>  $token]) : true;
            }
        } else {
            return   $this->create(100, '账号密码错误');
        }
    }
}
